﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Timetable.Base.Interfaces.Services;
using Timetable.Base.Entities;
using Timetable.Base.Interfaces.Repositories;
using Timetable.Base.Interfaces.Validators;
using Timetable.Base.Interfaces.Services.DataServices;
using Timetable.Utils.EventArgs;

namespace Timetable.Data.Services.DataServices
{
    public abstract class BaseDataService<T>: IDataService<T> where T: BaseEntity
    {
        public abstract IRepository<T> Repository { get; }

        public abstract IValidator<T> Validator { get; }

        public abstract IQueryable<T> All();

        public abstract T GetById(int id);

        public event EventHandler ValidationSuccess;

        public event EventHandler ValidationFail;

        public void Add(T item)
        {
            BaseCrudAction(item, Repository.Insert);
        }

        public void Update(T item)
        {
            BaseCrudAction(item, Repository.Update);
        }

        public void Delete(T item)
        {
            BaseCrudAction(item, Repository.Delete);
        }

        private void BaseCrudAction(T item, Action<T> action)
        {
        if (Validator.Validate(item))
            {
                if (ValidationSuccess != null)
                    ValidationSuccess(this, new ValidationSuccessEventArgs());

                action(item);
            }
            else
            {
                if (ValidationFail != null)
                    ValidationFail(this, new ValidationFailEventArgs { Errors = Validator.GetErrors() });
            }
        }
    }
}
